package com.example.falvback.service;

import com.example.falvback.entity.User;
import com.example.falvback.exception.ServiceException;
import com.example.falvback.mapper.LoginMapper;
import com.example.falvback.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 功能：
 * 作者：chen
 * 日期：2023/10/2410:16
 */
@Service

public class LoginService {
    @Autowired
    LoginMapper loginMapper;

    public User login(User user) {
        User dbUser = loginMapper.selectByUsername(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {//user.getPassword()是用户输入的密码，dbUser.getPassword()是数据库中的密码
            throw new ServiceException("用户名或密码错误");
        }
        //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    public User register(User user) {
        User dbUser = loginMapper.selectByUsername(user.getUsername());
        if (dbUser != null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setName(user.getUsername());
        loginMapper.insert(user);
        return user;
    }

}
